package xin.javashare.utils;

import java.util.Scanner;

/**
 * 程序清单6.8 【十六进制转十进制】
 * 使用霍纳算法
 */
public class Hex2Dec {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("输入一个十六进制数：");
        String hex = input.nextLine();

        System.out.println("转换为十进制数为：" + hexToDecimal(hex.toUpperCase()));
    }

    public static int hexToDecimal(String hex) {
        int decimalValue = 0;
        for (int i = 0; i < hex.length(); i++) {
            char hexChar = hex.charAt(i);
            decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
        }
        return decimalValue;
    }

    public static int hexCharToDecimal(char hexChar) {
        if (hexChar >= 'A' && hexChar <= 'F')
            return 10 + hexChar - 'A';
        else
//			System.out.println(hexChar -'0');
            return hexChar - '0';
    }
}
